<?php
/**
* Modules2buy
*
* @category   Application_Extensions
* @package    Flashgame
* @version    $Id: Core.php 6850 2010-07-26 22:25:26Z YouNet $
* @author     To Anh
*/

class Flashgame_Api_Core extends Core_Api_Abstract
{
    const IMAGE_WIDTH = 720;
    const IMAGE_HEIGHT = 720;

    const THUMB_WIDTH = 90;
    const THUMB_HEIGHT = 90;
    // Select
    /**
    * Gets a paginator for flashgames
    *
    * @param Core_Model_Item_Abstract $user The user to get the messages for
    * @return Zend_Paginator
    */

    public function getPeriodtypes()
    {  
        return array('1'=>"day(s)",'2'=>"week(s)",'3'=>"month(s)",'4'=>"year(s)");
    }
    public function getVersionSE()
    {
      $c_table  = Engine_Api::_()->getDbTable('modules', 'core');
      $c_name   = $c_table->info('name');
      $select   = $c_table->select()
                        ->where("$c_name.name LIKE ?",'core')->limit(1);
      
      $row = $c_table->fetchRow($select)->toArray();
      $strVersion = $row['version'];
      $intVersion = (int)str_replace('.','',$strVersion);
      return  $intVersion >= 410?true:false;
    }
    public function getFlashgamesPaginator($params = array(), $customParams = null)
    {
        if (isset($params['rates']) && $params['rates'] == '1')
            $paginator = Zend_Paginator::factory($this->getRatingsSelect());
        else
            $paginator = Zend_Paginator::factory($this->getFlashgamesSelect($params, $customParams));

        if( !empty($params['page']) )
        {
            $paginator->setCurrentPageNumber($params['page']);
        }
        if( !empty($params['limit']) )
        {
            $paginator->setItemCountPerPage($params['limit']);
        }

        return $paginator;
    }

    /**
    * Gets a select object for the user's Flashgame entries
    *
    * @param Core_Model_Item_Abstract $user The user to get the messages for
    * @return Zend_Db_Table_Select
    */
    public function getFlashgamesSelect($params = array(), $customParams = null)
    {
        $table = Engine_Api::_()->getDbtable('flashgames', 'flashgame');
        $rName = $table->info('name');

        $tmTable = Engine_Api::_()->getDbtable('TagMaps', 'core');
        $tmName = $tmTable->info('name');

        $searchTable = Engine_Api::_()->fields()->getTable('flashgame', 'search')->info('name');

        $select = $table->select()
        ->order( !empty($params['orderby']) ? $rName.'.'.$params['orderby'].' DESC' : $rName.'.flashgame_id DESC' );
        //die(print_r($params));

        if(isset($customParams)){

            $select = $select
            ->setIntegrityCheck(false)
            ->from($rName)
            ->joinLeft($searchTable, "$searchTable.item_id = $rName.flashgame_id")
            ->group("$rName.flashgame_id");
            if (!empty($customParams))
            {
                foreach ($customParams as $key => $param){
                    /*
                    if(!empty($param)){
                    $select = $select->where($searchTable.'.'.$key.' like ?', "%$param%");
                    }
                    */
                    if ($key == 'price' && (!empty($param['min']) && !empty($param['max']))){
                        if ($param['max']<$param['min']){
                            $min = $param['max'];
                            $max = $param['min'];
                        }
                        else{
                            $min = $param['min'];
                            $max = $param['max'];
                        }

                        $select = $select->where($searchTable.'.price >= ?', "$min")->where($searchTable.'.price <= ?', "$max");
                    }

                    if ($key == 'price' && (empty($param['min']) && !empty($param['max']))){
                        $select = $select->where($searchTable.'.price <= ?', $param['max']);
                    }

                    if ($key == 'price' && (!empty($param['min']) && empty($param['max']))){
                        $select = $select->where($searchTable.'.price >= ?', $param['min']);
                    }

                }
            }
        }

        if( !empty($params['user_id']) && is_numeric($params['user_id']) )
        {
            $select->where($rName.'.owner_id = ?', $params['user_id']);
        }

        if (isset($params['closed']))
        {
            $select->where($rName.'.closed = ?', $params['closed']);
        }

        if (isset($params['rates']) && $params['rates'] == '1')
        {
            $select->where($rName.'.rates > 0');
        }
        if( !empty($params['user']) && $params['user'] instanceof User_Model_User )
        {
            $select->where($rName.'.owner_id = ?', $params['user_id']->getIdentity());
        }

        if( !empty($params['users']) )
        {
            $str = (string) ( is_array($params['users']) ? "'" . join("', '", $params['users']) . "'" : $params['users'] );
            $select->where($rName.'.owner_id in (?)', new Zend_Db_Expr($str));
        }

        if( !empty($params['tag']) )
        {
            $select
            ->setIntegrityCheck(false)
            ->joinLeft($tmName, "$tmName.resource_id = $rName.flashgame_id")
            ->where($tmName.'.resource_type = ?', 'flashgame')
            ->where($tmName.'.tag_id = ?', $params['tag']);
        }

        if( !empty($params['category']) )
        {
            $select->where($rName.'.category_id = ?', $params['category']);
        }
        /*
        if( isset($params['closed']) && $params['closed']!="" )
        {
        $select->where($rName.'.closed = ?', $params['closed']);
        }
        */
        // Could we use the search indexer for this?
        if( !empty($params['search']) )
        {
            $select->where($rName.".title LIKE ? OR ".$rName.".body LIKE ?", '%'.$params['search'].'%');
        }
        /*
        if( !empty($params['start_date']) )
        {
        $select->where($rName.".creation_date > ?", date('Y-m-d', $params['start_date']));
        }

        if( !empty($params['end_date']) )
        {
        $select->where($rName.".creation_date < ?", date('Y-m-d', $params['end_date']));
        }
        */
        return $select;
    }
    /**
    * Gets a select object for the user's Flashgame entries
    *
    * @param Core_Model_Item_Abstract $user The user to get the messages for
    * @return Zend_Db_Table_Select
    */

    public function getRatingsSelect()
    {
        $table = Engine_Api::_()->getDbtable('flashgames', 'flashgame');
        $select = $table->select()
        ->order( 'rates DESC' )
        ->where('rates > 0')
        ->where('closed = 0');   
        return $select;
    }
    public function getPackages()
    {
        $table  = Engine_Api::_()->getDbTable('packages', 'flashgame');
        $uName = Engine_Api::_()->getDbtable('userpackages', 'flashgame')->info('name');
        $usName = Engine_Api::_()->getDbtable('users', 'user')->info('name');
        //client_user_id 
        $iName = $table->info('name');
        $select = $table->select()
        ->setIntegrityCheck(false)
        ->from($iName, "$iName.*, count($usName.user_id) as totalusers")
        ->joinLeft($uName, "$uName.userpackage_package_id = $iName.package_id")
        ->joinLeft($usName, "$uName.userpackage_user_id = $usName.user_id")
        ->group("package_id");
        return $table->fetchAll($select);

        //return Engine_Api::_()->getDbtable('packages', 'flashgame')->fetchAll();
    }
    public function getClients()
    {
        return  Engine_Api::_()->getDbtable('clients', 'flashgame')->select()->order('clients_id DESC');
    }

    public function getTotalClients()
    {
        return count(Engine_Api::_()->getDbtable('clients', 'flashgame')->fetchAll());
    }  
    public function getClientsPaginator($params = array(), $customParams = null)
    {
        $paginator = Zend_Paginator::factory($this->getClients());
        if( !empty($params['page']) )
        {
            $paginator->setCurrentPageNumber($params['page']);
        }
        if( !empty($params['limit']) )
        {
            $paginator->setItemCountPerPage($params['limit']);
        }

        return $paginator;
    }

    public function getIncomesPaginator($client_id)
    {
        $paginator = Zend_Paginator::factory($this->getIncomes($client_id));
        if( !empty($params['page']) )
        {
            $paginator->setCurrentPageNumber($params['page']);
        }
        if( !empty($params['limit']) )
        {
            $paginator->setItemCountPerPage($params['limit']);
        }

        return $paginator;
    }
    public function getIncomes($client_id)
    {     
        $table  = Engine_Api::_()->getDbTable('clients', 'flashgame');
        $hName = Engine_Api::_()->getDbtable('userpaymenthistory', 'flashgame')->info('name');
        $pName = Engine_Api::_()->getDbtable('paymentinfo', 'flashgame')->info('name');
        $uName = Engine_Api::_()->getDbtable('users', 'user')->info('name');

        //client_user_id 
        $iName = $table->info('name');
        $select = $table->select()
        ->setIntegrityCheck(false)
        ->from($iName)
        ->joinLeft($hName, "$hName.userpaymenthistory_client_id = $iName.clients_id")
        ->joinLeft($uName, "$uName.user_id = $iName.client_user_id")
        ->joinLeft($pName, "$pName.txnid = $hName.userpaymenthistory_txnid")
        ->where($iName.'.clients_id = ?', $client_id);    
        return $table->fetchAll($select);
    }

    public function getEnablePackages()
    {
        //userpackage_user_id 
        $table  = Engine_Api::_()->getDbTable('packages', 'flashgame');
        $rName = $table->info('name');
        $select = $table->select()
        ->from($rName)
        ->where($rName.'.package_enabled = ?', '1');
        return $table->fetchAll($select);
    }

    public function getPackage($package_id)
    {
        return Engine_Api::_()->getDbtable('packages', 'flashgame')->find($package_id)->current();
    }

    public function getFlashgame($flashgame_id)
    {
        return Engine_Api::_()->getDbtable('flashgames', 'flashgame')->find($flashgame_id)->current();
    }

    public function canRate($flashgame,$user_id)
    {
        if ($flashgame->owner_id == $user_id)
            return 0;
        $rateTable = Engine_Api::_()->getDbtable('rates', 'flashgame');
        $select = $rateTable->select()
        ->where('game_id = ?', $flashgame->getIdentity())
        ->where('poster_id = ?', $user_id);

        return (count($rateTable->fetchAll($select)) > 0)?0:1;   
    }

    public function getAVGrate($flashgame_id)
    {
        $rateTable = Engine_Api::_()->getDbtable('rates', 'flashgame');
        $select = $rateTable->select()
        ->from($rateTable->info('name'), 'AVG(rate_number) as rates')
        ->group("game_id")
        ->where('game_id = ?', $flashgame_id);
        $row = $rateTable->fetchRow($select);
        return ((count($row) > 0)) ? $row->rates : 0;
    }

    public function getCategories()
    {
        return Engine_Api::_()->getDbtable('categories', 'flashgame')->fetchAll();
    }

    public function getCategory($category_id)
    {
        return Engine_Api::_()->getDbtable('categories', 'flashgame')->find($category_id)->current();
    }

    public function getBePlayedGame($user_id)
    {
        //userpackage_user_id 
        $table  = Engine_Api::_()->getDbtable('userpackages', 'flashgame');
        /*
        $uName = Engine_Api::_()->getDbtable('userpackages', 'flashgame')->info('name');
        $iName = $table->info('name');
        */
        $select = $table->select()
        /*->where($iName.'.package_level_id <= ?', $game_level)*/
        /*->where($iName.'.package_enabled = ?', '1')*/
        ->where('UNIX_TIMESTAMP(userpackage_expiredate) >= ?', strtotime('now'))
        ->where('userpackage_user_id = ?', $user_id);
        $row = $table->fetchAll($select);
        return count($row);
    }

    public function getMaxExpiredate($user_id)
    {
        $table  = Engine_Api::_()->getDbtable('userpackages', 'flashgame');
        $select = $table->select()
        ->from($table->info('name'), 'MAX(UNIX_TIMESTAMP(userpackage_expiredate)) as expiredate')
        ->where('UNIX_TIMESTAMP(userpackage_expiredate) >= ?', strtotime('now'))
        ->where('userpackage_user_id = ?', $user_id);
        $maxdate =  mktime(0,0,0, date("m"), date("d"), date("Y"));         
        $row = $table->fetchRow($select);
        if (count($table->fetchAll($select)) > 0 && !empty($row->expiredate))
            $maxdate = $row->expiredate;
        return $maxdate; 
    }
    
    public function checkEnablePayMent()
    {
        //userpackage_user_id 
        $table  = Engine_Api::_()->getDbtable('paymentgateways', 'flashgame');
        $select = $table->select()
        ->where('paymentgateway_enabled = ?', '1');
        $row = $table->fetchAll($select);
        return count($row);
    }
    
    public function getEnablePackagesToUpgrade($user_id)
    {
        //userpackage_user_id 
        $table  = Engine_Api::_()->getDbTable('packages', 'flashgame');  
        $Usepackages = $this->getUserPackages($user_id);
        $str = array();
        if (count($Usepackages)>0)
            foreach ($Usepackages as $Usepackage){
                $str[] = $Usepackage->userpackage_package_id;
        }                  
        $select = $table->select()
        ->where('package_id not in (?)', implode(",",$str));
        return $table->fetchAll($select);
    }

    public function getUserPackages($user_id)
    {
        //userpackage_user_id 
        $table  = Engine_Api::_()->getDbTable('userpackages', 'flashgame');
        //$pName = Engine_Api::_()->getDbtable('packages', 'flashgame')->info('name');
        //$rName = $table->info('name');
        $select = $table->select()
        //->setIntegrityCheck(false)
        //->from($rName)
        //->joinLeft($pName, "$pName.package_id = $rName.userpackage_package_id")
        /*->where('UNIX_TIMESTAMP('.$rName.'.userpackage_expiredate) >= ?', strtotime('now'))*/
        ->where('userpackage_user_id = ?', $user_id);
        return (count($table->fetchAll($select)) > 0)?$table->fetchAll($select):false;

    }

    public function getPackageUser($package_id, $user_id)
    {
        $table  = Engine_Api::_()->getDbTable('userpackages', 'flashgame');
        $uName = Engine_Api::_()->getDbtable('users', 'user')->info('name');        
        $rName = $table->info('name');

        $select = $table->select()
        ->setIntegrityCheck(false)
        ->from($rName)
        ->joinLeft($uName, "$uName.user_id = $rName.userpackage_user_id")
        ->where($rName.'.userpackage_user_id = ?', $user_id)
        ->where($rName.'.userpackage_package_id = ?', $package_id);
        return $table->fetchRow($select);
    }  

    public function getPackageUsers($package_id)
    {
        $table  = Engine_Api::_()->getDbTable('userpackages', 'flashgame');
        $uName = Engine_Api::_()->getDbtable('users', 'user')->info('name');        
        $rName = $table->info('name');

        $select = $table->select()
        ->setIntegrityCheck(false)
        ->from($rName)
        ->joinInner($uName, "$uName.user_id = $rName.userpackage_user_id")
        ->where($rName.'.userpackage_package_id = ?', $package_id);
        return $table->fetchAll($select);
    }  

    public function getPackageLevels()
    {    
        $table  = Engine_Api::_()->getDbtable('packages', 'flashgame');
        $lName = Engine_Api::_()->getDbtable('levels', 'authorization')->info('name');
        $iName = $table->info('name');
        $select = $table->select()
        ->setIntegrityCheck(false)
        ->from($iName)
        ->where($iName.".package_enabled = '1'")
        ->group($iName.".package_level_id")
        ->joinLeft($lName, "$lName.level_id = $iName.package_level_id");
        return $table->fetchAll($select);
    }

    public function getUserCategories($user_id)
    {
        $table  = Engine_Api::_()->getDbtable('categories', 'flashgame');
        $uName = Engine_Api::_()->getDbtable('flashgames', 'flashgame')->info('name');
        $iName = $table->info('name');

        $select = $table->select()
        ->setIntegrityCheck(false)
        ->from($iName, array('category_name'))
        ->joinLeft($uName, "$uName.category_id = $iName.category_id")
        ->group("$iName.category_id")
        ->where($uName.'.owner_id = ?', $user_id);

        return $table->fetchAll($select);
    }
    /*
    function getArchiveList($user_id = null)
    {

    $table = Engine_Api::_()->getDbtable('flashgames', 'flashgame');
    $rName = $table->info('name');

    $select = $table->select()
    //->setIntegrityCheck(false)
    ->from($rName);

    if( !empty($params['user_id']) && is_numeric($params['user_id']) )
    {
    $select->where($rName.'.owner_id = ?', $params['user_id']);
    }

    return $table->fetchAll($select);
    }
    */
    public function createGame($file,$params=array())
    {
        $game_path = pathinfo($file['name']);
        $game_params    = array(
        'parent_type' => 'flashgame',
        'parent_id'   => $params['flashgame_id'],
        );
        $name = basename($file['name']);
        $path = dirname($file['tmp_name']);
        $extension = ltrim(strrchr($file['name'], '.'), '.');
        $fileURL = $path.'/'.$name;
        $gamefile = Engine_Api::_()->storage()->create($fileURL, $game_params);
        return $gamefile->file_id;
    }

    public function createPhoto($params, $file)
    {
        if( $file instanceof Storage_Model_File )
        {
            $params['file_id'] = $file->getIdentity();
        }
        else
        {
            // Get image info and resize
            $name = basename($file['name']);
            $path = dirname($file['tmp_name']);
            //$extension = ltrim(strrchr($file['name'], '.'), '.');

            $thumbName = $path.'/'.$name;

            $image = Engine_Image::factory();
            $image->open($path.'/'.$name)
            ->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)
            ->write($thumbName)
            ->destroy();

            // Store files
            $photo_params = array(
            'parent_id' => $params['flashgame_id'],
            'parent_type' => 'flashgame',
            );
            $photoFile = Engine_Api::_()->storage()->create($thumbName, $photo_params);
            @unlink($thumbName);      
            /*
            $param['owner_type'] = $params['parent_type'];
            $param['owner_id'] = $params['parent_id'];
            unset($params['parent_type']);
            unset($params['parent_id']);
            */
        }

        return $photoFile->file_id;
    }
}
